package cool.taomu.toolkit.rpc.thrift.client.provider

import com.google.gson.reflect.TypeToken
import com.google.inject.Inject
import com.google.inject.Provider
import com.google.inject.name.Named
import cool.taomu.toolkit.entity.TaomuConfig
import cool.taomu.toolkit.rpc.thrift.entity.ThriftConfig
import cool.taomu.toolkit.rpc.thrift.service.ThriftConnectionFactory
import java.time.Duration
import java.util.List
import java.util.concurrent.ConcurrentHashMap
import org.apache.commons.pool2.impl.GenericObjectPool
import org.apache.commons.pool2.impl.GenericObjectPoolConfig
import org.apache.thrift.transport.TTransport
import org.eclipse.xtend.lib.annotations.Accessors
import org.slf4j.LoggerFactory

@Accessors
@Deprecated
class ThritfTHshaClientProvider implements Provider<ConcurrentHashMap<String, GenericObjectPool<TTransport>>> {
    val static LOG = LoggerFactory.getLogger(ThritfTHshaClientProvider);

    @Inject(optional=true)
    @Named("taomu.rpc.client.thrift")
    TaomuConfig config;

    @Inject(optional=true)
    @Named("taomu.thrift.client.pool.maxTotal")
    int maxTotal = 15

    @Inject(optional=true)
    @Named("taomu.thrift.client.pool.minIdle")
    int minIdle = 5

    @Inject(optional=true)
    @Named("taomu.thrift.client.pool.maxIdle")
    int maxIdle = 10

    override get() {
        if (config !== null) {
            var client = config.get(new TypeToken<List<ThriftConfig>>() {
            })
            val poolMap = new ConcurrentHashMap<String, GenericObjectPool<TTransport>>();
            client.forEach [
                if (!poolMap.containsKey(it.name)) {
                    var pool = getThriftClientPool(it.host, it.port, it.timeout);
                    poolMap.put(it.name, pool);
                }
            ]
            return poolMap;
        }
        new ConcurrentHashMap<String, GenericObjectPool<TTransport>>(0);
    }

    def getThriftClientPool(String host, int port, int timeout) {
        LOG.info("连接服务器=>{}:{}:{}", host, port, timeout);
        LOG.info("创建连接池")
        var config = new GenericObjectPoolConfig<TTransport>();
        config.setMaxTotal(maxTotal); // 最大连接数
        config.setMinIdle(minIdle); // 最小空闲连接数
        config.setMaxIdle(maxIdle); // 最大空闲连接数
        config.setMaxWait(Duration.ofSeconds(3));
        // 启用连接验证
        config.setTestOnBorrow(true); // 借用对象时验证
        config.setTestWhileIdle(true); // 空闲时验证
        config.setTimeBetweenEvictionRuns(Duration.ofSeconds(30)); // 清理间隔
        return new GenericObjectPool<TTransport>(new ThriftConnectionFactory(host, port, timeout), config);
    }

}
